package com.yifei.model.entity.auth;

import cn.hutool.core.util.ObjectUtil;
import com.yifei.model.dto.auth.UserAuthInfo;
import com.yifei.model.enums.EnableStatusEnum;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: Spring Security
 * @Author: yiFei
 * @date: 2023/9/17 21:13
 */
public class SysUserDetails implements UserDetails {
    /**
     * 用户 ID
     */
    private Long userId;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 是否启用
     */
    private Boolean enabled;
    /**
     * 角色
     */
    @Setter
    private Collection<SimpleGrantedAuthority> roles;
    /**
     * 权限
     */
    @Getter
    private Set<String> perms;

    /**
     * 构建 SysUserDetails
     *
     * @param userAuthInfo 通过其创建 SysUserDetails
     */
    public SysUserDetails(UserAuthInfo userAuthInfo) {
        this.userId = userAuthInfo.getUserId();
        // 重构角色名，方便 SpringSecurity 使用
        Set<String> roles = userAuthInfo.getRoles();
        if (!CollectionUtils.isEmpty(roles)) {
            // 在权限模型中，角色和权限是有区别的，SpringSecurity规定所有角色前需要有一个 ROLE_
            this.roles = roles.stream()
                    // 标记角色，在使用
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                    .collect(Collectors.toSet());
        } else {
            // 如果没有角色信息，赋值为空集合
            this.roles = Collections.emptySet();
        }
        this.username = userAuthInfo.getUsername();
        this.password = userAuthInfo.getPassword();
        // 通过查看用户状态表示是否可用
        this.enabled = ObjectUtil.equal(userAuthInfo.getStatus(), EnableStatusEnum.ENABLE.getValue());
        this.perms = userAuthInfo.getPerms();
    }

    public Long getUserId() {
        return this.userId;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.roles;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
